package com.joe.xl.demo.thread;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class DeadLockDemo {
    /***
     * 查看堆栈死锁信息
     * 1. jps
     * 2. jstack pid
     * @param args
     */
    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock();

        deadLock.setFlag("a");
        Thread thread1 = new Thread(deadLock);
        thread1.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        deadLock.setFlag("b");
        Thread thread2 = new Thread(deadLock);
        thread2.start();
    }


    static class DeadLock implements Runnable{
        private String username;
        public Object object1 = new Object();
        public Object object2 = new Object();

        public void setFlag(String username) {
            this.username = username;
        }

        public void run() {
            if(Objects.equals(username, "a")){
                synchronized (object1){
                    System.out.println("username1.." + username);

                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (object2){
                        System.out.println("o1 -> o2");
                    }
                }
            }

            if(Objects.equals(username, "b")){
                synchronized (object2){
                    System.out.println("username2.." + username);

                    try {
                        TimeUnit.SECONDS.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    synchronized (object1){
                        System.out.println("o2 -> o1");
                    }
                }
            }
        }

    }
}
